import { Component, OnInit } from '@angular/core';
import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
import { EmitterService } from '../../../service/emit.service';
import { ProductService } from '../../../service/prod/product.service';

@Component({
    selector: 'product-sku-edit-v2',
    styleUrls: ['./product-sku-edit-v2.component.less'],
    templateUrl: './product-sku-edit-v2.component.html' 
})
export class ProductSkuEditV2Component implements OnInit {        
    attrList = ['图片', '型号', '色号', 'SKU', 'SAP',
        '结算价', '批发价', '市场价',
        '镜框材质', '镜框颜色', '镜片材质', '镜片颜色', '镜腿材质', '镜腿颜色', '产品规格'];
    dataTable = [];
    uploadUrl = '';
    batch = [];
    

    constructor(
        private msg: NzMessageService, 
        private modalService: NzModalService,
        private emit: EmitterService,
        private productService: ProductService
    ) {
        
    }

    ngOnInit() {
        this.uploadUrl = this.productService.uploadUrl();
        // 构建数据表 默认5行
        this.dataTable = [[], [], [], [], []];
        this.batch = [];   
    }
    
    pasteExcel(row, col, e) {   
        let CHAR = '\r\n';
        if ("Windows" !== this.getOS()) {
            CHAR = '\n';
        }
        for (let item of e.clipboardData.items) {
            if (item.type === 'text/plain') {
                item.getAsString((text) => {
                    let x = col,
                        y = row,
                      obj = {};
                    text = text.trim(CHAR);
                    text.split(CHAR).forEach((v2, i2) => {
                        v2.split('\t').forEach((v3, i3) => {
                            let newRow = y + i2, newCol = x + i3;
                            if (this.dataTable[newRow]) {                                
                                this.dataTable[newRow][newCol] = v3;
                            }
                            
                        })
                    })  
                })
            }
        }         
    }

    mergeStyleColor() {
        for (let row = 0; row < this.dataTable.length; row++) { 
            if (this.dataTable[row][1] || this.dataTable[row][2]) {               
                this.dataTable[row][3] = ((this.dataTable[row][1]+"") + (this.dataTable[row][2] + "")).replace('/', '');
            }
        }
    }

    append() {
        if (this.dataTable.length >= 10) {
            return;
        }
        this.dataTable.push([]);        
    }

    batchEdit(index) {        
        for (let row = 0; row < this.dataTable.length; row++) {                
            this.dataTable[row][index] = this.batch[index];
        }        
    }

    beforeUpload = (file: File) => {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
            this.msg.warning(`不支持的格式: ${file.type}`);            
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            this.msg.warning('图片不能超过2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
    }

    private getBase64(img: File, callback: (img: any) => void) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    handleChange(row, col, info: { file: UploadFile }) {
        if (info.file.status === 'uploading') {            
            return;
        }
        if (info.file.status === 'done') {  
            let that = this;   
            let f = info;       
            this.getBase64(info.file.originFileObj, (img: any) => {  
                that.dataTable[row][col] = {
                    id: f.file.response.rows[0].id, url: img
                };
            });
        }
        if (info.file.status === 'error') {
            this.msg.error(info.file.error.error);
        }
    }

    getOS() {
        var userAgent = window.navigator.userAgent,
            platform = window.navigator.platform,
            macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
            windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
            iosPlatforms = ['iPhone', 'iPad', 'iPod'],
            os = null;
      
        if (macosPlatforms.indexOf(platform) !== -1) {
          os = 'Mac OS';
        } else if (iosPlatforms.indexOf(platform) !== -1) {
          os = 'iOS';
        } else if (windowsPlatforms.indexOf(platform) !== -1) {
          os = 'Windows';
        } else if (/Android/.test(userAgent)) {
          os = 'Android';
        } else if (!os && /Linux/.test(platform)) {
          os = 'Linux';
        }
      
        return os;
    }    
}